package com.shwread.android.qysw.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View.OnClickListener;
import android.widget.ScrollView;

import com.NewActionHelp;
import com.ciko.code.base.BaseActicity;
import com.ciko.code.logic.bean.ContactBean;
import com.ciko.code.logic.bean.ContactSuperBean;
import com.ciko.code.logic.dao.ContactBookInfoDao;
import com.ciko.code.logic.dao.ContactGroupDao;
import com.ciko.code.utils.PerferencesUtil;
import com.google.gson.reflect.TypeToken;
import com.mywork.WorkUIKit;
import com.shwread.android.qysw10000204.R;
import com.shwread.android.ui.page.chat.adapter.NewContactGroupAdapter;
import com.shwread.http.base.ObjectHttpResponseHandler;

import org.apache.http.Header;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;


/**
 * @Project： qysw_1.1.6_association
 * @Title：ContactsPage
 * @Description：
 * @Author：wayne
 * @Date：2015年11月27日上午12:10:43
 */
public class ContactsActivity extends BaseActicity implements OnClickListener {

    public static int[] isClose;
    private com.ui.widget.refresh.internal.PullToRefreshScrollView contentView;
    private com.ui.widget.MyExpandableListView listView;
    private List<ContactSuperBean> groups = new ArrayList<>();
    private HashMap<String, List<com.ciko.code.logic.bean.ContactBookInfo>> contacts = new HashMap<>();
    private ProgressDialog progressDialog;
    private static final int PROGRESS_SHOW = 111;
    private static final int PROGRESS_HIDE = 112;
    private static final int REFRESH_DATA = 113;
    private Context context;

    private NewContactGroupAdapter adapter;
    //数据库相关
    private ContactGroupDao groupDao;
    private ContactBookInfoDao ContactBookInfoDao;
    private String name = "";
    private int companyId = -1;

    private PerferencesUtil utils;
    /**
     * 是否在搜索框
     */
    private long lastTimeStamp;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case PROGRESS_SHOW:
                    progressDialog = ProgressDialog.show(context, "", "正在初始化...");
                    break;
                case PROGRESS_HIDE:
                    progressDialog.dismiss();
                    break;
                case REFRESH_DATA:
                    getDataFromDb();
                    showData();
                    break;
            }
        }
    };


    @Override
    protected void initTopBar() {
        name = getIntent().getStringExtra("name");
        companyId = getIntent().getIntExtra("companyId", -1);
        Log.e("通讯录companyId", companyId + "");
        setTitle(name);
        enableNavLeftImg();
    }

    @Override
    protected void initLayout() {
        setContentView(R.layout.activity_contact);
        context = this;
    }

    @Override
    protected void initView() {
        contentView = (com.ui.widget.refresh.internal.PullToRefreshScrollView) findViewById(R.id.approver_psview);
        com.ui.widget.refresh.internal.PullToRefreshUtil.initLabel(this, contentView);
        listView = (com.ui.widget.MyExpandableListView) findViewById(R.id.contacts_list);

    }

    @Override
    protected void initAdapter() {
    }

    @Override
    protected void initDates() {
        groupDao = ContactGroupDao.getInstance(context);
        ContactBookInfoDao = ContactBookInfoDao.getInstance(context);

        utils = PerferencesUtil.getInstance(context);
        String userId = WorkUIKit.getUserId();
        if (!utils.getLastLoginUser().equals(userId)) {//判断是否是同一用户,切换用户删除数据库
            groupDao.deleteAll();
            ContactBookInfoDao.deleteAll();
            utils.clearAllData();
            utils.setLastLoginUser(userId);
        }
        lastTimeStamp = utils.getContactLastTimeStamp();
        NewActionHelp.qryEnterpriseAddressBookList(context, lastTimeStamp, new GetAddressBookListHandler());
    }

    @Override
    protected void initListener() {
        contentView.setOnRefreshListener(new com.ui.widget.refresh.base.PullToRefreshBase.OnRefreshListener<ScrollView>() {
            @Override
            public void onRefresh(com.ui.widget.refresh.base.PullToRefreshBase<ScrollView> refreshView) {
                if (contentView.isHeaderShown()) {
                    refrush();
                } else if (contentView.isFooterShown()) {
                    boolean isAllClose = true;
                    int i;
                    for (i = 0; i < isClose.length; i++) {
                        if (isClose[i] == 1) {
                            isAllClose = false;
                            break;
                        }
                    }
                    if (!isAllClose) {
                        ContactSuperBean group = groups.get(i);
                        List<com.ciko.code.logic.bean.ContactBookInfo> list = contacts.get(group.getName());
                        if (list.size() < group.getAddressBookList().size()) {
                            int size = list.size();
                            for (int j = list.size(); j < group.getAddressBookList().size() && j < size + 50; j++) {
                                list.add(group.getAddressBookList().get(j));
                            }
                            contacts.put(group.getName(), list);
                            adapter.notifyDataSetChanged();
                        }
                    }
                    contentView.onRefreshComplete();
                }
            }
        });

    }

    /**
     * 组内排序
     */
    private void sortContacts() {
        List<com.ciko.code.logic.bean.ContactBookInfo> contacts;
        com.ciko.code.logic.bean.ContactBookInfo contact;
        for (ContactSuperBean group : groups) {
            contacts = group.getAddressBookList();
            for (int i = 0; i < contacts.size() - 1; i++) {
                for (int j = i; j < contacts.size(); j++) {
                    if (contacts.get(i).getSortNum() > contacts.get(j).getSortNum()) {
                        contact = contacts.get(i);
                        contacts.set(i, contacts.get(j));
                        contacts.set(j, contact);
                    }
                }
            }
            group.setAddressBookList(contacts);
        }
    }

    /**
     * 组排序
     */
    private void sortGroups() {
        ContactSuperBean bean;
        for (int i = 0; i < groups.size() - 1; i++) {
            for (int j = i + 1; j < groups.size(); j++) {
                if (groups.get(i).getSortNum() < groups.get(j).getSortNum()) {
                    bean = groups.get(i);
                    groups.set(i, groups.get(j));
                    groups.set(j, bean);
                }
            }
        }
    }

    /**
     * 下拉刷新
     */
    private void refrush() {
//        listView.setVisibility(View.GONE);
        initDates();
    }

    public class GetAddressBookListHandler extends ObjectHttpResponseHandler<ContactBean> {
        @Override
        public Type getType() {
            return new TypeToken<ContactBean>() {
            }.getType();
        }

        @Override
        public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) {
        }

        @Override
        public void onSuccess(final int arg0, Header[] arg1, final ContactBean arg2, String arg3) {
            Log.e("通讯录具体员工", arg3);
            lastTimeStamp = arg2.getLastTimeStamp();
            utils.setContactLastTimeStamp(lastTimeStamp);
            if (arg2 != null && arg2.getGroupList() != null && arg2.getGroupList().size() > 0) {
                new Thread() {
                    @Override
                    public void run() {
                        groups = arg2.getGroupList();
                        putDataToDB();
                    }
                }.start();
            } else {
                handler.sendEmptyMessage(REFRESH_DATA);
            }
        }
    }

    /**
     * 数据库存储
     */
    private void putDataToDB() {
        handler.sendEmptyMessage(PROGRESS_SHOW);
        for (ContactSuperBean group : groups) {
            if (groupDao.getById(group.getGroupId()) != null) {
                groupDao.update(group);
            } else {
                groupDao.add(group);
            }
            for (com.ciko.code.logic.bean.ContactBookInfo ContactBookInfo : group.getAddressBookList()) {
                if (ContactBookInfoDao.getById(ContactBookInfo.getContactId(), group.getGroupId()) != null) {
                    ContactBookInfoDao.update(ContactBookInfo);
                } else {
                    ContactBookInfoDao.add(ContactBookInfo);
                }
            }
        }
        handler.sendEmptyMessage(PROGRESS_HIDE);
        handler.sendEmptyMessage(REFRESH_DATA);

    }

    /**
     * 查询所有
     */
    private void getDataFromDb() {
        groups.clear();
        List<ContactSuperBean> dbGroups = groupDao.getAll(companyId);
        if (dbGroups == null) {
            return;
        } else {
            for (int i = 0; i < dbGroups.size(); i++) {
                List<com.ciko.code.logic.bean.ContactBookInfo> addressBookList = new ArrayList<>();
                List<com.ciko.code.logic.bean.ContactBookInfo> dbList = ContactBookInfoDao.getListByGroupId(dbGroups.get(i).getGroupId(), companyId);
                for (com.ciko.code.logic.bean.ContactBookInfo info : dbList) {
                    if (info.getIsDelete().equals("n")) {
                        addressBookList.add(info);
                    }
                }
                dbGroups.get(i).setAddressBookList(addressBookList);
            }
            for (ContactSuperBean group : dbGroups) {
                if (group.getAddressBookList() != null && group.getAddressBookList().size() != 0) {
                    groups.add(group);
                }
            }
        }
    }

    private void showData() {
        sortGroups();
        sortContacts();
        int p = 0;
        isClose = new int[groups.size()];
        for (ContactSuperBean group : groups) {
            List<com.ciko.code.logic.bean.ContactBookInfo> list = new ArrayList<>();
            if (group.getAddressBookList().size() > 50) {
                for (int i = 0; i < 50; i++) {
                    list.add(group.getAddressBookList().get(i));
                }
            } else {
                list.addAll(group.getAddressBookList());
            }
            contacts.put(group.getName(), list);
            isClose[p] = 0;
            p++;
        }
        Collections.reverse(groups);
        adapter = new NewContactGroupAdapter(context, listView, groups, contacts);
        listView.setAdapter(adapter);
        listView.setGroupIndicator(null);
        listView.setFocusable(false);
        listView.setFocusableInTouchMode(false);
        contentView.onRefreshComplete();
        //若适配器中无数据隐藏布局
    }

}
